<?php

/**
 * This is the model class for table "{{base_category}}".
 *
 * The followings are the available columns in table '{{base_category}}':
 * @property integer $cat_id
 * @property string $cat_name
 */
class BaseCategoryModel extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{base_category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
		    array('cat_name', 'required','message'=>'{attribute}不允许为空'),
			array('cat_name', 'length', 'max'=>90),
		    array('cat_name', 'unique','message'=>'{attribute}已经存在'),
			array('sort,parent_id', 'numerical', 'integerOnly'=>true),
			array('pids', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('cat_id, cat_name, sort', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'parent'=>array(self::BELONGS_TO,'BaseCategoryModel','parent_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'cat_id' => 'Cat',
			'parent_id' => '上级分类',
			'cat_name' => '分类名称',
			'sort' => '排序',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('cat_id',$this->cat_id);
		$criteria->compare('parent_id',$this->parent_id);
		$criteria->compare('cat_name',$this->cat_name,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	protected function afterDelete() {
		// 删除订单详细资料
		BaseCategoryModel::model()->deleteAll('pids like "%,'.$this->cat_id.',%"');
		parent::afterDelete();
	}
	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	//获取分类的数据
	public static function getCategoryData($module_name){
		$model=BaseCategoryModel::model()->findAll('1 order by sort desc');
		$arr = array();
		foreach ($model as $v){
			$str_manage = array();
			$str_manage[]=CHtml::link('添加下级分类',Yii::app()->createUrl($module_name.'/category/create',array('parent_id'=>$v->cat_id)));
			if(Yii::app()->user->checkAccess('category|update')){
				$str_manage[]=CHtml::link('编辑',Yii::app()->createUrl($module_name.'/category/update',array('id'=>$v->cat_id)));
			}
			if(Yii::app()->user->checkAccess('category|delete')){
				$str_manage[]=CHtml::link('删除','javascript:void(0);',array('url'=>Yii::app()->createUrl($module_name.'/category/delete',array('id'=>$v->cat_id)),'class'=>'delete'));
			}
			$arr[]=array(
					'id'=>$v->cat_id,
					'parentid'=>$v->parent_id,
					'cat_name'=>$v->cat_name,
					'str_manage'=>!empty($str_manage)?join(' ', $str_manage):''
			);
		}
		return $arr;
	}
	//获取分类
	static public function get_category($is_first=""){
		$sql = 'select * from {{base_category}} order by sort desc';
		$result = Yii::app()->db->createCommand($sql)->queryAll();
		if($is_first){
			$re = array(0=>'请选择');
		}else{
			$re = array();
		}
		foreach ($result as $v){
			$re[$v['cat_id']] = $v['cat_name'];
		}
		return $re;
	}
    /**
     * BaseCategoryModel::getCategoryJson() 获取栏目层极JSON
     * 
     * @param string $fid
     * @return json
     */
    public function getCategoryJson($fid=''){
		$where = 'where 1 ';
		if(!empty($fid)){
			$where.=' and parent_id="'.$fid.'"';
		}
		$sql = 'select * from {{base_category}} '.$where.' order by cat_id asc';
		$menuAll = Yii::app()->db->createCommand($sql)->queryAll();
		$menu=array();
		$result=array();
		foreach ($menuAll as $v){
			$result[$v['cat_id']]=$v;
		}
		foreach ($result as $k=>$v){
			$fid=$v['parent_id'];
			if($fid==0){
				$menu[]=&$result[$k];
			}else{
				$result[$fid]['child'][$k]=&$result[$k];//引用当前循环的这一个值，为其找到父级
			}
		}
		$return_menu = $this->getChildCategory($menu,$fid);
		$jGoodsClass = json_encode($return_menu);
		return $jGoodsClass;
	}
	/**
	 * BaseCategoryModel::getChildCategory()
	 * 
	 * @param mixed $menu
	 * @param mixed $cur_menu
	 * @return
	 */
	public function getChildCategory($menu,$cur_menu){
		if(empty($menu)) return false;
		$aReturn='';
		foreach ($menu as $v){
			if(isset($v['child']) && !empty($v['child'])){
				$aReturn[]=array(
								'text'=>$v['cat_name'],
								'id'=>$v['cat_id'],
								//'checked'=>in_array($v['menu_id'], $cur_menu)?true:false,
								//'checked'=>false,
								'expanded'=>true,
								'children'=>$this->getChildCategory($v['child'],$cur_menu)
						   );
			}else{
				$aReturn[]=array(
								'text'=>$v['cat_name'],
								'id'=>$v['cat_id'],
								//'checked'=>in_array($v['menu_id'], $cur_menu)?true:false,
								'expanded'=>true
						   );
			}
		}
		return $aReturn;
	}
}
